package Socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket;

    public UdpEchoServer(int port) throws SocketException {
        this.socket =new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            DatagramPacket request = new DatagramPacket(new byte[1024],1024);
            socket.receive(request);
String requestStr = new String(request.getData(),0,request.getLength());
String reponsestr=process(requestStr);
            DatagramPacket reponse=new DatagramPacket(reponsestr.getBytes(),reponsestr.getBytes().length,
                    request.getAddress(),request.getPort());
            socket.send(reponse);
            System.out.printf("IP:%s   port: %d  request:%s  reponse:%s\n",
                    request.getAddress(),request.getPort(),requestStr,reponsestr);
        }
    }

    private String process(String requestStr) {
        return requestStr;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server=new UdpEchoServer(8888);
        server.start();
    }

}
